package hibernate.web;

import hibernate.fileControler.MyException;
import hibernate.model.Kullanici;
import hibernate.service.EmmyService;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@SuppressWarnings("serial")
@Component("KullaniciBean")
//@Scope("session")
public class KullaniciBean implements BeanService, Serializable {

	@Autowired
	private transient EmmyService emmyService;

	private Kullanici currentKullanici;
	private Kullanici selectedUser;
	private List<Kullanici> kullaniciList;
	private Map<Long, String> userSessionMap;

	private MusteriBean musBean;
	private TemsilciBean temBean;
	private SirketprofilBean firmaBean;

	private FacesContext facesContext;
	private HttpServletRequest request;
	private HttpSession httpSession;

	@Override
	@PostConstruct
	public void init() {
		currentKullanici = new Kullanici();
		userSessionMap = new HashMap<Long, String>();
	}

	@Override
	public String restart() {
		init();
		return "detay";
	}

	@Override
	public String deleteView() {
		emmyService.delete(currentKullanici.getKullaniciid());
		init();
		return "list";
	}

	@Override
	public String viewNew() {
		currentKullanici = new Kullanici();
		return "detail";
	}

	@Override
	public String viewDetail() {
		/*
		 * List<Kullanici> valueList = (List<Kullanici>)
		 * kullaniciTable.getValue();
		 * System.out.println("table size : "+valueList.size());
		 * Iterator<SimpleRowKey> keys =
		 * kullaniciTable.getSelection().getKeys();
		 * 
		 * if(keys.hasNext()){ currentKullanici=
		 * valueList.get(keys.next().intValue());
		 * System.out.println("dolu = "+currentKullanici.getKullaniciid());
		 * return "detail"; }else{ System.out.println("bo�ta"); return null; }
		 */return "detay";
	}

	@Override
	public String SaveOrUpdate() throws MyException {
		emmyService.saveOrUpdate(currentKullanici);
		init();
		return "list";
	}

	@SuppressWarnings("unchecked")
	public String getDetayliKullanici() {
		kullaniciList = (List<Kullanici>) emmyService.getQuery(createQuery());
		return "list";
	}

	@Override
	public String createQuery() {
		Kullanici klc = currentKullanici;
		String query = "from Kullanici";

		if (klc == null) {
			return query;
		}
		if (klc.getGrup() != 0) {
			if (query.indexOf("where") != -1) {
				query += " and grup=" + klc.getGrup() + "";

			} else {
				query += " where grup=" + klc.getGrup() + "";
			}
		}
		if (klc.getKullaniciAdi() != null) {
			if (query.indexOf("where") != -1) {
				query += " and kullaniciAdi=" + klc.getKullaniciAdi() + "";

			} else {
				query += " where kullaniciAdi=" + klc.getKullaniciAdi() + "";
			}
		}
		return query;
	}

	public void logout(ActionEvent actionEvent) {
		getSession();
		userSessionMap.remove(((Kullanici) httpSession
				.getAttribute("currentKullanici")).getKullaniciid());
		httpSession.removeAttribute("currentKullanici");
		if (currentKullanici.getGrup() == 1) {
			System.out.println("grup 1");
			emmyService.clearSession(musBean);
			emmyService.clearSession(new MusteriAygitlariBean());
		} else {
			System.out.println("grup :" + currentKullanici.getGrup());
			emmyService.clearSession(temBean);
			emmyService.clearSession(firmaBean);
		}
		emmyService.clearSession(new AygitBean());
		// Kullanıcı hariç hepsini silmenin yolunu bul

		FacesMessage msg = null;
		msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Goodbye",
				currentKullanici.getKullaniciAdi());
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public void login(ActionEvent actionEvent) {
		RequestContext context = RequestContext.getCurrentInstance();

		FacesMessage msg = null;
		boolean loggedIn = false;
		System.out.println("kul adı:" + currentKullanici.getKullaniciAdi());
		System.out.println("prl : " + currentKullanici.getParola());

		if (currentKullanici.getKullaniciAdi() != null
				&& currentKullanici.getParola() != null) {
			try {
				if (loginControl(currentKullanici) == 1) {
					if (currentKullanici.getGrup() == 1) {
						System.out.println("grup 1");
						musBean = (MusteriBean) emmyService.getBean(new MusteriBean());
						musBean.setCurrentMusteri(currentKullanici.getMusteri());
					} else {
						System.out.println("grup :"+ currentKullanici.getGrup());
						temBean = (TemsilciBean) emmyService.getBean(new TemsilciBean());
						temBean.setCurrentTemsilci(currentKullanici.getTemsilci());

						firmaBean = (SirketprofilBean) emmyService.getBean(new SirketprofilBean());
						firmaBean.setCurrentSirketpro(currentKullanici.getTemsilci().getSirketprofil());
					}
					msg = new FacesMessage(FacesMessage.SEVERITY_INFO,
							"Welcome", currentKullanici.getKullaniciAdi());
					loggedIn = true;
				} else if (loginControl(currentKullanici) == 2) {
					if (currentKullanici.getGrup() == 1) {
						musBean = (MusteriBean) emmyService.getBean(new MusteriBean());
						musBean.setCurrentMusteri(currentKullanici.getMusteri());
					} else {
						temBean = (TemsilciBean) emmyService.getBean(new TemsilciBean());
						temBean.setCurrentTemsilci(currentKullanici.getTemsilci());

						firmaBean = (SirketprofilBean) emmyService.getBean(new SirketprofilBean());
						firmaBean.setCurrentSirketpro(currentKullanici.getTemsilci().getSirketprofil());
					}
					msg = new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Warning", "Diğer oturum kapatıldı");
					loggedIn = true;
				} else {
					msg = new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Login Error", "Invalid credentials");
					loggedIn = false;
				}
			} catch (Exception e) {
				loggedIn = false;
				System.out.println("error : " + e.toString());
				msg = new FacesMessage(FacesMessage.SEVERITY_WARN,
						"Login Error", "Hatalı giriş");
			}
		} else {
			loggedIn = false;
			msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error",
					"Invalid credentials");
		}
		FacesContext.getCurrentInstance().addMessage(null, msg);
		context.addCallbackParam("loggedIn", loggedIn);
	}

	public int loginControl(Kullanici currentKlc) {
		Kullanici klc = (Kullanici) emmyService.getQuery("findKlcKulAdi",
				"kKulAdi", currentKullanici.getKullaniciAdi()).get(0);

		if (klc.getParola().equals(currentKlc.getParola())) {
			if (!userSessionMap.containsKey(klc.getKullaniciid())) {
				currentKullanici = klc;
				System.out.println("login OK.");
				addUserToContext(klc);
				return 1; // login successful
			} else {
				currentKullanici = klc;
				userSessionMap.remove(klc.getKullaniciAdi());
				System.out.println("kullanıcı oturumu açık");
				addUserToContext(klc);
				return 2; // loign OK and other open session was closed
			}
		}
		return 0; // login unsuccessful
	}

	public void addUserToContext(Kullanici klc) {
		getSession();
		httpSession.setAttribute("currentKullanici", klc);
		userSessionMap.put(klc.getKullaniciid(), httpSession.getId());
		System.out.println("id: " + httpSession.getId());
	}

	public void verifyUser(ComponentSystemEvent event) {
		getSession();
		try {
			System.out.println("kullaniciBean");
			if (!userSessionMap.containsValue(httpSession.getId())) {
				httpSession.removeAttribute("currentKullanici");
			}
		} catch (java.lang.NullPointerException nle) {
			System.out.println("verify error : " + nle);
		}
	}

	@Override
	public void getSession() {
		facesContext = FacesContext.getCurrentInstance();
		request = (HttpServletRequest) facesContext.getExternalContext()
				.getRequest();
		httpSession = request.getSession(false);
	}

	public Kullanici getCurrentKullanici() {
		return currentKullanici;
	}

	public void setCurrentKullanici(Kullanici currentKullanici) {
		this.currentKullanici = currentKullanici;
	}

	public Kullanici getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(Kullanici selectedUser) {
		this.selectedUser = selectedUser;
	}

	public List<Kullanici> getKullaniciList() {
		return kullaniciList;
	}

	public void setKullaniciList(List<Kullanici> kullaniciList) {
		this.kullaniciList = kullaniciList;
	}

	public Map<Long, String> getUserSessionMap() {
		return userSessionMap;
	}

	public void setUserSessionMap(Map<Long, String> userSessionMap) {
		this.userSessionMap = userSessionMap;
	}

	public FacesContext getFacesContext() {
		return facesContext;
	}

	public void setFacesContext(FacesContext facesContext) {
		this.facesContext = facesContext;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpSession getHttpSession() {
		return httpSession;
	}

	public void setHttpSession(HttpSession httpSession) {
		this.httpSession = httpSession;
	}

	public MusteriBean getMusBean() {
		return musBean;
	}

	public void setMusBean(MusteriBean musBean) {
		this.musBean = musBean;
	}

	public TemsilciBean getTemBean() {
		return temBean;
	}

	public void setTemBean(TemsilciBean temBean) {
		this.temBean = temBean;
	}

	public SirketprofilBean getFirmaBean() {
		return firmaBean;
	}

	public void setFirmaBean(SirketprofilBean firmaBean) {
		this.firmaBean = firmaBean;
	}
}